package com.dudu.service.impl;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.dudu.access.ChengQiUtil;
import com.dudu.access.IMSDialUtils;
import com.dudu.access.RongLianUtils;
import com.dudu.access.TianYiUtil;
import com.dudu.access.YonYouUtil;
import com.dudu.bean.AccountBean;
import com.dudu.bean.AppExtendBean;
import com.dudu.bean.ChargingRuleBean;
import com.dudu.bean.DialResultBean;
import com.dudu.bean.MeetInfoBean;
import com.dudu.bean.PoolAbilityInfoBean;
import com.dudu.enumeration.AbilityTypeEnum;
import com.dudu.service.IConferenceDialService;
import com.dudu.service.IConferenceManageInfoService;
import com.dudu.service.IOperationPlatformService;
import com.dudu.service.IRecordInfoService;
import com.dudu.service.IRuleService;
import com.dudu.timer.SendVoiceUtil;
import com.dudu.utils.DictionaryUtils;

import core.CoreDao;
import core.CoreDaoInvoke;

/**
 * 用于一对一通话业务--发起通话
 * 
 * @author weidong
 * 
 */
public class ConferenceDialServiceImpl implements IConferenceDialService {
    private static final Logger log = core.util.Logger.getLogger(ConferenceDialServiceImpl.class.getSimpleName());
    // 录音文件处理
    private IRecordInfoService recordInfoServiceImpl = new RecordInfoServiceImpl();
    // 能力配置查询
    private IRuleService ruleService = new RuleServiceImpl();
    // 用于查询数据用
    private CoreDao coreDao = CoreDaoInvoke.getInstance();
    // 用于记录通话相应信息
    private IConferenceManageInfoService conferenceManageInfoService = new ConferenceManageInfoServiceImpl();
    // 运营平台接口
    private IOperationPlatformService operationPlatformService = new OperationPlatformServiceImpl();
    private String RongLianDialTicket = DictionaryUtils.getValueByTypeAndKey("url", "RongLianDialTicket");
    private String tianYiDialTicket = DictionaryUtils.getValueByTypeAndKey("tianYi", "ticketUrl");

    /**
     * 用于发起一对一通话
     * 
     * @param appExtendBean
     *            应用扩展实体类
     * @param accountBean
     *            账号实体类
     * @param caller
     *            主叫
     * @param called
     *            被叫
     * @param userIdentify
     *            用户标识
     * @param displayNbrMode
     *            被叫显号模式
     * @param displayNbr
     *            主叫来电显示号码（为空则随机选择配置的号码）
     * @param 强制使用平台号
     * @return
     */
    @Override
    public JSONObject doDial(AppExtendBean appExtendBean, AccountBean accountBean, String caller, String called, String userIdentify, String isRecord, String displayNbrMode,
	    String displayNbr, String usePlatNbr) {
	log.info("ConferenceDialServiceImpl.doDial");
	// 用于后期返回值
	JSONObject object = new JSONObject();
	// 获取双方通话能力类型标识
	String abilityType = AbilityTypeEnum.DIAL.getKey();
	// 获取账号能力配置
	ChargingRuleBean chargingRule = ruleService.queryChargingRule(appExtendBean.getApp_key(), accountBean.getCust_account(), abilityType);
	// 判断查询的默认通道调用数据是否为空
	if (chargingRule != null) {
	    // String displayNum = null;//显号
	    String pool_ability_id = null;
	    String number_vest = null;// 地区
	    SendVoiceUtil sendUtil = new SendVoiceUtil();
	    PoolAbilityInfoBean poolAbilityInfo = sendUtil.queryPoolAbilityInfo(coreDao, appExtendBean.getApp_key(), accountBean.getCust_account(), chargingRule.getType(),
		    pool_ability_id, displayNbr, usePlatNbr, number_vest);
	    if (poolAbilityInfo == null) {
		if (AbilityTypeEnum.DiAl_RONGLIAN.getKey().equals(chargingRule.getType())) {
		    poolAbilityInfo = new PoolAbilityInfoBean();
		} else {
		    object.put("result", "-1");
		    object.put("errorMsg", "未配置对应显号;ability_type:" + chargingRule.getType());
		    object.put("describe", "未配置显号");
		    object.put("code", "0018");
		    object.put("sessionId", "");
		    object.put("displayNbr", "");
		    return object;
		}
	    }
	    if (AbilityTypeEnum.DIAL_IMS.getKey().equals(chargingRule.getType())) {
		// IMS点击拨号
		object = doDail(appExtendBean, accountBean, poolAbilityInfo, caller, called, userIdentify, chargingRule.getType(), isRecord, displayNbrMode);
	    } else if (AbilityTypeEnum.DiAl_RONGLIAN.getKey().equals(chargingRule.getType())) {
		// 容联点击拨号
		object = doDail(appExtendBean, accountBean, poolAbilityInfo, caller, called, userIdentify, chargingRule.getType(), isRecord, displayNbrMode);
	    } else if (AbilityTypeEnum.DIAL_TIANYI.getKey().equals(chargingRule.getType())) {
		/**
		 * 天亿默认不录音，因为天亿只有企业才可以配置是否录音，接口不支持录音设置，所以暂时没有放开
		 */
		object = doDail(appExtendBean, accountBean, poolAbilityInfo, caller, called, userIdentify, chargingRule.getType(), "0", displayNbrMode);
	    } else if (AbilityTypeEnum.DIAL_CHENGQI.getKey().equals(chargingRule.getType())) {
		// 承启通点击拨号
		object = doDail(appExtendBean, accountBean, poolAbilityInfo, caller, called, userIdentify, chargingRule.getType(), isRecord, displayNbrMode);
	    } else if (AbilityTypeEnum.DIAL_YONYOU.getKey().equals(chargingRule.getType())) {
		// 自建
		object = doDail(appExtendBean, accountBean, poolAbilityInfo, caller, called, userIdentify, chargingRule.getType(), isRecord, displayNbrMode);
	    } else {
		object.put("result", "-1");
		object.put("errorMsg", "未配置对应通道！voice_type:" + chargingRule.getType());
		object.put("describe", "未配置线路");
		object.put("code", "0010");
		object.put("sessionId", "");
		object.put("displayNbr", "");
	    }
	} else {
	    object.put("result", "-1");
	    object.put("describe", "能力配置错误");
	    object.put("code", "0013");
	    object.put("sessionId", "");
	    object.put("displayNbr", "");
	}
	return object;
    }

    /**
     * 用于发起一对一通话--IMS
     * 
     * @param appExtendBean
     *            应用扩展实体类
     * @param accountBean
     *            账号实体类
     * @param poolAbilityInfo
     *            能力
     * @param caller
     *            主叫
     * @param called
     *            被叫
     * @param userIdentify
     *            用户标识
     * @param ability_type
     *            能力类型
     * @param isRecord
     *            是否录音1 为录音，0为不录音，默认0
     * @param displayNbrMode
     *            被叫显号模式
     * @return
     */
    private JSONObject doDail(AppExtendBean appExtendBean, AccountBean accountBean, PoolAbilityInfoBean poolAbilityInfo, String caller, String called, String userIdentify,
	    String ability_type, String isRecord, String displayNbrMode) {
	JSONObject object = new JSONObject();
	try {
	    // 判断相应参数是否为空
	    // if (StringUtils.isBlank(caller) || StringUtils.isBlank(called)) {
	    // object.put("result", "-1");
	    // object.put("describe", "主持人号码、参与人号码不能为空");
	    // object.put("code", "0020");
	    // return object;
	    // }
	    DialResultBean diaresult = null;
	    if (AbilityTypeEnum.DIAL_IMS.getKey().equals(ability_type)) {
		// IMS 点击拨号
		diaresult = IMSDialUtils.dial(caller, called, poolAbilityInfo, isRecord, displayNbrMode);
	    } else if (AbilityTypeEnum.DiAl_RONGLIAN.getKey().equals(ability_type)) {
		// 容联
		diaresult = RongLianUtils.dial(caller, called, poolAbilityInfo.getDisplay_number(), RongLianDialTicket, isRecord, displayNbrMode);
	    } else if (AbilityTypeEnum.DIAL_TIANYI.getKey().equals(ability_type)) {
		// 天亿
		diaresult = TianYiUtil.dial(caller, called, poolAbilityInfo.getDisplay_number(), tianYiDialTicket, isRecord, displayNbrMode, "");
	    } else if (AbilityTypeEnum.DIAL_CHENGQI.getKey().equals(ability_type)) {
		// 承启通
		diaresult = ChengQiUtil.dial(caller, called, poolAbilityInfo.getDisplay_number(), isRecord);
	    } else if (AbilityTypeEnum.DIAL_YONYOU.getKey().equals(ability_type)) {
		// 自建
		diaresult = YonYouUtil.dial(caller, called, poolAbilityInfo.getDisplay_number(), isRecord);
	    } else {
		object.put("result", "-1");
		object.put("errorMsg", "未配置对应通道！voice_type:" + ability_type);
		object.put("code", "0010");
		object.put("describe", "未配置线路");
		object.put("sessionId", "");
		object.put("displayNbr", "");
	    }
	    if (null != diaresult && diaresult.getResult().equals("0")) {
		object.put("sessionId", diaresult.getSessionId());
		object.put("displayNbr", diaresult.getDisplayNbr());
		object.put("result", "0");
		object.put("describe", "拨号发起成功");
		object.put("code", "0000");
		this.saveMeetInfo(object, appExtendBean, accountBean, poolAbilityInfo.getCharge_number(), ability_type, userIdentify, caller, called, isRecord,
			diaresult.getSessionId());
	    } else {
		object.put("result", "-1");
		object.put("describe", "拨号发起失败");
		object.put("code", "0401");
		object.put("sessionId", "");
		object.put("displayNbr", "");
	    }

	} catch (Exception e) {
	    object.put("result", "-1");
	    object.put("errorMsg", "会议发起失败" + e);
	    object.put("describe", "拨号发起失败");
	    object.put("code", "0401");
	    object.put("sessionId", "");
	    object.put("displayNbr", "");
	}
	return object;
    }

    /**
     * 保存会议信息
     * 
     * @param object
     * @param appExtendBean
     * @param accountBean
     * @param charge_number
     * @param callType
     * @param userIdentify
     * @param caller
     * @param called
     * @param isRecord
     * @param sessionId
     */
    private void saveMeetInfo(JSONObject object, AppExtendBean appExtendBean, AccountBean accountBean, String charge_number, String callType, String userIdentify, String caller,
	    String called, String isRecord, String sessionId) {
	String messages = "会议发起成功";
	// 在运营平台注册用户信息
	if (!operationPlatformService.manageUserByOP(appExtendBean.getPeriphery_code(), accountBean.getCust_account(), userIdentify)) {
	    messages = messages + ",在运营平台注册用户信息失败！";
	}
	// 存储会议信息
	// 拼写会议信息bean
	MeetInfoBean meetInfoBean = new MeetInfoBean();
	meetInfoBean.setAbility_type(callType);
	meetInfoBean.setApp_key(appExtendBean.getApp_key());
	meetInfoBean.setCalled(called);
	meetInfoBean.setCaller(caller);
	meetInfoBean.setChargeNumber(charge_number);
	meetInfoBean.setComments("");
	meetInfoBean.setCust_account(accountBean.getCust_account());
	meetInfoBean.setDuration(0);
	meetInfoBean.setPeriphery_code(appExtendBean.getPeriphery_code());
	meetInfoBean.setSession_id(sessionId);
	meetInfoBean.setStatus("0");
	// 计算人数
	String[] calledNumbers = called.split(",");
	meetInfoBean.setTotal_amount(calledNumbers.length + 1);
	meetInfoBean.setUser_identify(userIdentify);

	if (!conferenceManageInfoService.manageMeetInfo(meetInfoBean)) {
	    messages = messages + ",会议信息存储失败！";
	}
	// 处理录音文件信息
	if ("1".equals(isRecord)) {
	    this.recordInfoServiceImpl.insert(coreDao, object.getString("sessionId"), AbilityTypeEnum.CALLRECORDER_IMS.getKey(), appExtendBean, accountBean);
	}
	// 将拼好的返回信息插入object
	object.put("describe", messages);
    }
}
